const api = require('../../utils/api.js');
const tools = require('../../utils/getuserinfo.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

Page({
  data: {
    windowHeight: wx.systemInfo.windowHeight,
    position: true,
    message: '',
    t_m_show: -1,
    msglist: [],
    page: 1,
    more: true,
    abnorData: {
      imgSrc: '/common/static/images/abnor-09.png',
      text: '暂无留言',
    },
    imgUrl: app.imgUrl,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
  },

  onLoad(opts) {
    wx.hideShareMenu();
    app.v8_card_action_log = [];
    let that = this;
    let options = opts || {};
    let user_id = options.user_id;
    let parent_id = 0;
    let shop_id = 0;
    let share_scene = '';
    let share_from = '';
    let scene = decodeURIComponent(options.scene);
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
      shop_id = options.shopid;
    }
    if (options && options.from) {
      share_from = options.from;
    }
    app.tabbarindex = options.tabbarindex
      ? options.tabbarindex - 0
      : app.tabbarindex;
    app.pageOnLoad(this);
    if (user_id) {
      parent_id = user_id;
      share_scene = 4;
    } else if (scene) {
      //  0  topic_id, 1  user_id, 2  shop_id
      let scene_obj = scene.split(',');
      console.log('scene_obj', scene_obj);
      if (scene_obj[1] && scene_obj[0]) {
        parent_id = scene_obj[1];
        options.id = scene_obj[0];
        options.guide_id = scene_obj[1];
        options.shopid = scene_obj[2];
        shop_id = scene_obj[2];
        app.ws_micro_shop_globalData.shopid = scene_obj[2];
      } else {
        parent_id = scene;
      }
      share_scene = 6;
    }
    let userinfo = wx.getStorageSync('user_info');
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);
    if (userinfo) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      if (user_id) {
        app.loginBindParent({
          parent_id,
          shop_id,
          share_scene,
        });
      }
      util.prepareBindInfo(options, moduleName, that);
      app.bindGuide(options);
      app.bindCard(options.openid, options.share_scene);
      app.v8_card_action_log.push({ name: 'transmitArticle', data: { articleID: options.id }, timestamp: new Date().getTime(), to_openid: options.openid});
      util.statRequest({
        aa: JSON.stringify(app.v8_card_action_log)
      });
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 &&
          tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        app.bindGuide(options);
        app.bindCard(options.openid, options.share_scene);
        app.v8_card_action_log.push({ name: 'transmitArticle', data: { articleID: options.id }, timestamp: new Date().getTime(), to_openid: options.openid});
        util.statRequest({
          aa: JSON.stringify(app.v8_card_action_log)
        });
        app.getStoreData().then(res => {
          if (user_id) {
            app.loginBindParent({
              parent_id,
              shop_id,
              share_scene,
            });
          }
        });
      });
    }
    that.setData({
      opts: options,
      useTabbar:that.data.useTabbar && app.getTabBarStatus(),
      share_from,
      isSaas: app.ws_micro_shop_globalData.isSaas,
    });
    app.ws_micro_shoprequest({
      url: api.default.topic,
      data: {
        id: options.id,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData(res.data, () => {
            this.__timer = setTimeout(() => {
              that.setData({ showAttachments: true }); // 附件不要早于富文本渲染
            }, 1000);
          });
          // wx.setNavigationBarTitle({
          //   title: res.data.title || '专题详情',
          // });
          Number(res.data.t_m_show) === 0 && that.loadMessage();
          wx.createSelectorQuery()
            .select('.body')
            .boundingClientRect(function(rect) {
              if (rect.height - 60 >= that.data.windowHeight) {
                that.setData({
                  position: false,
                });
              }
            })
            .exec();
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(e) {
              if (e.confirm) {
                app.util.navigateTo('/ws_micro_shop/pages/index/index');
              }
            },
          });
        }
      },
    });
  },

  loadMessage() {
    let that = this;
    let { page, more, opts, msglist } = that.data;
    let id = opts.id;
    if (more) {
      app.ws_micro_shoprequest({
        url: api.default.leavemsg,
        data: {
          id,
          page,
          limit: 10,
        },
        success: function(resp) {
          if (resp.code === 0) {
            let list = resp.data.list;
            let imgList = [];
            msglist = msglist.concat(list);
            if (list.length > 0) {
              page += 1;
              that.setData({
                more: true,
                page,
              });
            } else {
              // wx.showToast({
              //   title: '没有更多留言了',
              //   icon: 'none',
              // });
              that.setData({
                more: false,
              });
            }
            for (let i in msglist) {
              if (Object.prototype.hasOwnProperty.call(msglist, i)) {
                let item = msglist[i];
                if (item.pictures) {
                  imgList = item.pictures.split(',');
                  msglist[i].imgList = imgList;
                }
              }
            }
            that.setData({
              msglist,
            });
          }
        },
      });
    }
  },

  getMessage(e) {
    let msg = e.detail.value;
    this.setData({
      message: msg,
    });
  },

  submitMsg() {
    let that = this;
    let topic_id = this.data.opts.id;
    let content = this.data.message ? this.data.message.trim() : '';
    let pictures = this.data.uploadImg ? this.data.uploadImg : '';
    let userinfo;
    let time;
    let msglist;
    if (Number(that.data.t_m_show) === 0) {
      userinfo = wx.getStorageSync('user_info');
      time = app.util.formatTime(new Date().getTime() / 1000);
      msglist = that.data.msglist;
    }
    if (content === '' && pictures === '') {
      wx.showToast({
        title: '留言内容或图片不能为空',
        icon: 'none',
      });
    } else {
      wx.showLoading({
        title: '正在提交',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.default.topicLetter,
        data: {
          topic_id,
          content,
          pictures,
        },
        method: 'POST',
        success: function(resp) {
          if (resp.code === 0) {
            wx.hideLoading();
            wx.showToast({
              title: resp.msg || '留言成功',
              icon: 'none',
            });
            if (Number(that.data.t_m_show) === 0) {
              msglist.unshift({
                nickname: userinfo.nickname,
                avatar_url: userinfo.avatar_url,
                content,
                addtime: time,
                imgList: that.data.uploadImg ? that.data.uploadImg : '',
              });
              that.setData({
                msglist,
              });
            }
            wx.pageScrollTo({
              scrollTop: 0,
              duration: 300,
            });
            that.setData({
              message: '',
              uploadImg: '',
            });
          }
        },
      });
    }
  },

  wxmlTagATap(e) {
    let src = e.detail.src || false;
    let reUrl = /^\//;
    if (!src) {
      return;
    } else {
      if (reUrl.test(src)) {
        app.util.navigateTo('/ws_micro_shop' + src);
      } else {
        app.util.navigateTo('/ws_micro_shop/pages/web/web', { url: src });
      }
    }
  },

  favoriteClick(e) {
    let that = this;
    let action = e.currentTarget.dataset.action;
    app.ws_micro_shoprequest({
      url: api.user.topic_favorite,
      data: {
        topic_id: that.data.id,
        action: action,
      },
      success: function(res) {
        wx.showToast({
          title: res.msg || '',
          icon: 'success',
          duration:1500
        });
        if (res.code === 0) {
          that.setData({
            is_favorite: action,
          });
        }
      },
    });
  },

  onShareAppMessage() {
    let user_info = wx.getStorageSync('user_info');
    let { id, share_title, share_pic, title } = this.data;
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    let path =
      '/ws_micro_shop/pages/topic/topic?id=' +
      id +
      '&user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid +
      '&openid=' +
      openid;
    path = util.spliceSharePath(path, '4', moduleName);
    let res = {
      title: share_title || title,
      path,
      imageUrl: share_pic || '',
    };
    return res;
  },

  onShareTimeline() {
    let user_info = wx.getStorageSync('user_info');
    let { id, share_title, share_pic, title } = this.data;
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    return {
      title: share_title || title,
      imageUrl: share_pic || '',
      query: 'id=' +
      id +
      '&user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid +
      '&openid=' +
      openid
    }
  },

  onHide() {
    util.sendBindInfo(this.data);
    clearTimeout(this.__timer);
  },

  onUnload() {
    util.sendBindInfo(this.data);
    clearTimeout(this.__timer);
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  showShareModal() {
    wx.pageScrollTo({
      scrollTop: 0,
    });
    this.setData({
      share_modal_active: 'active',
    });
  },

  shareModalClose() {
    this.setData({
      share_modal_active: '',
    });
  },

  getGoodsQrcode() {
    let _this = this;
    _this.setData({
      goods_qrcode_active: 'active',
      share_modal_active: '',
    });
    if (_this.data.goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.default.topicqrcode,
      data: {
        topic_id: _this.data.opts.id,
      },
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            goods_qrcode: res.data.pic_url,
          });
        }
        if (res.code === 1) {
          _this.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },

  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
    });
  },

  saveGoodsQrcode() {
    let _this = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content:
          '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          _this.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          _this.downLoadGoodsImg();
        }
      },
    });
  },

  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function(e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function() {
            wx.showModal({
              title: '提示',
              content: '专题海报保存成功',
              showCancel: false,
            });
          },
          fail: function(e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function(e) {
            wx.hideLoading();
          },
        });
      },
      fail: function(e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function(e) {
        wx.hideLoading();
      },
    });
  },

  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },

  disabledClick() {
    // it`s necessary
  },

  attachAction(e) {
    let { type, url, fileType = '' } = e.currentTarget.dataset;
    url && wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    url &&
      wx.downloadFile({
        url,
        success: res => {
          if (res.statusCode === 200) {
            let path = res.tempFilePath;
            type === 'preview' &&
              wx.openDocument({
                filePath: path,
                fileType,
              });
            type === 'download' &&
              wx.saveFile({
                tempFilePath: path,
                success: res => {
                  wx.showToast({
                    title: '保存成功',
                  });
                },
              });
          }
        },
        complete: () => {
          wx.hideLoading();
        }
      });
  },

  uploadPicturesEvent(e) {
    let uploadImg = e.detail.myImg.length !== 0 ? e.detail.myImg : '';
    this.setData({ uploadImg });
  },

  previewUpImage(e) {
    let that = this;
    let { url, index } = e.currentTarget.dataset;
    wx.previewImage({
      current: url,
      urls: that.data.msglist[index].imgList,
    });
  },
});
